package com.swu.pad.system.service.impl;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.swu.pad.assignment.dao.AssignmentDao;
import com.swu.pad.assignment.entity.Assignment;
import com.swu.pad.comment.dao.ConnectDatabase;
import com.swu.pad.system.dao.UserDao;
import com.swu.pad.system.entity.User;
import com.swu.pad.system.entity.Users;
import com.swu.pad.system.service.UserService;
import com.swu.pad.util.StringUtil;
import com.swu.pad.util.EPLiteClient.EPLiteClient;

@Service
@Transactional
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDao userDao;
	@Autowired
	private EntityManager entityManager;
	@Autowired
	private AssignmentDao assignmentdao;
	@Autowired
	private EPLiteClient epliteClient;

	public User saveUser(User user) {
		if (!StringUtil.isValid(user.getId())) {
			String authorId = epliteClient.createAuthorIfNotExistsFor(user.getUsername()).get("authorID").toString();
			user.setId(authorId);
		}
		return userDao.save(user);
	}

	public User findUserById(String id) {
		return userDao.findUserById(id);
	}

	public User login(String username, String password) {
		User user = userDao.findUserByUsernameAndPassword(username, password);
		entityManager.clear();// 使对象变成游离状态，不再自动更新
		if (user != null)
			user.setPassword("");
		return user;
	}

	@Override
	public List<Users> findUserBygroupName(String groupName,String assignmentId) {
		Assignment assignment =assignmentdao.findAssignmentById(assignmentId);
		String courseId=assignment.getCourseId();
		Connection conn = null;// 连接数据库
		PreparedStatement pstmt = null;
		ResultSet rs=null;
		List<Users> users=new ArrayList<Users>();
		try {
			conn = ConnectDatabase.getConnection();
			String SQL="select * from course_group_user where group_name=? and course_id=? ";
			pstmt = (PreparedStatement) conn.prepareStatement(SQL);
			pstmt.setString(1,groupName);
			pstmt.setString(2,courseId);
			rs=pstmt.executeQuery();
			if(rs!=null){
				while (rs.next())
				{ 
				
					Users user=new Users();
					user.setId(rs.getString("user_id"));
					user.setName(rs.getString("user_name"));
					users.add(user);
				}
				
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("查询发生异常！");
		}
		return users;
	}

}
